package com.aruba.clientapplication

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.widget.TextView
import com.aruba.serviceapplication.IMyAidlInterface
import com.aruba.serviceapplication.RequestData

class MainActivity : AppCompatActivity() {
    var myAidlInterface: IMyAidlInterface? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 隐式调用
        val intent = Intent("com.aruba.service").apply {
            `package` = "com.aruba.serviceapplication"//设置服务端的包名
        }

        bindService(intent, object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                myAidlInterface = IMyAidlInterface.Stub.asInterface(service)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                myAidlInterface = null
            }

        }, 0)
    }

    /**
     * 发送消息
     */
    fun send(view: android.view.View) {
        // 调用Ibinder的send方法
        myAidlInterface?.send(RequestData("hello i'm client")).let {
            (findViewById(R.id.textView) as TextView).text = it?.data
        }
    }
}